<?php

namespace app\admin\controller;

use app\common\Helper;
use app\admin\model\Store as StoreMdl;
use app\admin\model\Type;
use app\admin\model\Advertise;
use app\admin\model\Ticket;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 店铺
 */
class Store extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $this->model = new StoreMdl();
    }

    /**
     * 店铺首页
     */
    public function getStoreHome(){
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['status'] = ['neq', 2];
        $where = $defaultWhere;

        if (isset($param->typeId)) {
            $where['typeId'] = $param->typeId;
        }
        if (isset($param->province)) {
            //$where['province'] = $param->province;
            if($param->province != '所有'){
                $where['province'] = $param->province;
            }
        }
        if (isset($param->city)) {
            //$where['city'] = $param->city;
            if($param->city != '所有'){
                $where['city'] = $param->city;
            }
        }
        /*if (isset($param->area)) {
            if($param->area != '市辖区'){
                $where['area'] = $param->area;
            }
        }*/
        if (isset($param->storeName)) {
            $where['name'] = ['like', '%' . $param->storeName . '%'];
        }
        if (isset($param->status)) {
            if (!in_array($param->status, [1, 2, 3])) {
                return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'status 格式不正确');
            }
            if($param->status == 1){
                // 待审核
                $where['status'] = 0;
            }else if($param->status == 2){
                // 已上架
                $where['status'] = 1;
            }else{
                // 已下架
                $where['status'] = 4;
            }
        }
        $model = $this->model;
        $order = 'createDate DESC';
        $result = $model->where($where)->limit($start, $length)->order($order)->select();
        $total = $model->where($where)->count();

        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关店铺');
        }

        foreach ($result as $item) {
            $item['typeName'] = Type::where(['id' => $item['typeId']])->value('typeName');
            //$item['countTicket'] = db('specialofferruleconnect')->where(['storeId' => $item['id']])->count();
            $item['countTicket'] = db('ticket')->where(['storeId' => $item['id'], 'status' => ['neq', 3]])->count();
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 详情
     */
    public function detail(){
        $param = self::getHttpParam();
        $model = $this->model;

        if (empty($param->storeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'storeId 不能这空');
        }

        $id = $param->storeId;
        $where = [
            'id' => $id
        ];
        $fields = '*';
        $item = $model->where($where)->field($fields)->find();

        if (empty($item)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关店铺');
        } else {
            $item['typeName'] = Type::where(['id' => $item['typeId']])->value('typeName');
            //$item['countTicket'] = db('specialofferruleconnect')->where(['storeId' => $item['id']])->count();
            $item['countTicket'] = db('ticket')->where(['storeId' => $item['id']])->count();

            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
        }
    }

    /**
     * 删除
     */
    public function delete(){
        $param = self::getHttpParam();
        $model = $this->model;

        if (empty($param->storeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'storeId 不能为空');
        }

        $id = $param->storeId;
        Db::startTrans();
        try {
            //$result = $model->where('id', $id)->delete();
            $result = $model->where('id', $id)->update(['status' => 2]);
            if($result !== false){
                // 删除用户与店铺关联
                db('userstore')->where(['storeId' => $id])->delete();

                // 广告关联操作
                //$this->updateAdvertise($id, 3);
                // 优惠券关联操作
                $this->updateTicket($id, 3);

                // Query执行后的操作
                $model->_after_delete($id);

                Db::commit();
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '删除成功');
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $e->getMessage());
        }
    }

    /**
     * 审核通过/店铺上架/下架
     */
    public function handle(){
        $param = self::getHttpParam();
        $model = $this->model;

        if (empty($param->storeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'storeId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2, 3])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }

        $id = $param->storeId;
        //$info = $model->where('id', $id)->find();
        Db::startTrans();
        try {
            if($param->type == 1){
                // 通过
                $data['status'] = 1;
                $result = $model->allowField(true)->save($data, ['id' => $id]);
            }else if($param->type == 2){
                // 上架
                $data['status'] = 1;
                $result = $model->allowField(true)->save($data, ['id' => $id]);
                $status = 1;
            }else{
                // 下架
                $data['status'] = 4;
                $result = $model->allowField(true)->save($data, ['id' => $id]);
                $status = 2;
            }

            if($result !== false){
                if(isset($status)){
                    // 广告关联操作
                    //$this->updateAdvertise($id, $status);
                    // 优惠券关联操作
                    $this->updateTicket($id, $status);
                }

                Db::commit();
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '操作成功');
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $e->getMessage());
        }
    }

    /**
     * 获取分类
     */
    public function getTypeTree(){
        $where = [

        ];
        $options = Type::where($where)->field('id as typeId, typeName')->select();

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $options);
    }

    /**
     * 更新广告
     */
    public function updateAdvertise($storeId, $status){
        if(!$storeId || !$status){
            return false;
        }

        $where = [
            'b.storeId' => $storeId
        ];
        if($status == 1){
            // 上架操作，则条件为已下架的
            $where['a.status'] = 2;
        }else{
            // 下架/删除 操作，则条件为已上架的
            $where['a.status'] = 1;
        }
        $join = [
            ['advertisestoreconnect b', 'b.advertiseId = a.id'],
        ];
        $data  = [
            'status' => $status
        ];
        $result = Advertise::alias('a')->where($where)->join($join)->update($data);

        if($result !== false){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 更新优惠券
     */
    public function updateTicket($storeId, $code){
        if(!$storeId || !$code){
            return false;
        }

        $where = [
            'storeId' => $storeId
        ];
        if($code == 1){
            // 上架操作，则条件为已下架的
            $where['status'] = 4;
            $status = 5;
        }elseif($code == 2){
            // 下架操作，则条件为已上架的
            $where['status'] = 5;
            $status = 4;
        }else{
            // 删除操作，则条件为已上架的
            $where['status'] = 5;
            $status = 3;
        }
        $data  = [
            'status' => $status
        ];
        if($code != 1){
            $result = Ticket::where($where)->update($data);
            if($result !== false){
                return true;
            }else{
                return false;
            }
        }

        return true;
    }

}